if (!geomanagement) {
	var geomanagement = {};
}
function clickButtonMostrar() {
	document.getElementById('mostrar').click();
}
(function($) {
	geomanagement.ControlPanel = function(element, baseUrl, onStart, onChange) {
		this.properties = {};
		this.markers = [];
		this.map = null;
		this.target = $(element);
		this.filter = null;
		this.baseUrl = baseUrl;
		this._init(onStart, onChange);

	};

	$
			.extend(
					geomanagement.ControlPanel.prototype,
					{
						_init : function(onStart, onChange) {
							var mapCenter = new google.maps.LatLng(-33.428075,
									-70.610003);
							var mapOptions = {
								zoom : 12,
								mapTypeId : google.maps.MapTypeId.ROADMAP,
								mapTypeControl : true,
								mapTypeControlOptions : {
									style : google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
									position : google.maps.ControlPosition.BOTTOM_CENTER
								},
								streetViewControl : true,
								streetViewControlOptions : {
									position : google.maps.ControlPosition.TOP_CENTER
								},
								zoomControl : true,
								zoomControlOptions : {
									style : google.maps.ZoomControlStyle.SMALL,
									position : google.maps.ControlPosition.BOTTOM_CENTER
								},
								scaleControl : true,
								scaleControlOptions : {
									position : google.maps.ControlPosition.TOP_LEFT
								},
								panControl : false,
								center : mapCenter
							};
							this.map = new google.maps.Map(this.target[0],
									mapOptions);

							var map = this.map;

							google.maps.event.addDomListener(window, "resize",
									function() {
										$('#main_content, .ui-panel-inner')
												.height(
														0.95 * $(window)
																.height());
										var center = map.getCenter();
										google.maps.event
												.trigger(map, "resize");
										map.setCenter(center);
									});
							google.maps.event
									.addListener(
											this.map,
											"bounds_changed",
											function() {
												if (gm.timer)
													clearTimeout(gm.timer);
												gm.timer = setTimeout(
														function() {
															jQuery("#search_form")[0].modified.value = 'true';
															var sw = map
																	.getBounds()
																	.getSouthWest();
															var ne = map
																	.getBounds()
																	.getNorthEast();
															var bbox = sw.lng()
																	+ " "
																	+ sw.lat();
															bbox = bbox + ","
																	+ sw.lng()
																	+ " "
																	+ ne.lat()
																	+ ","
																	+ ne.lng()
																	+ " "
																	+ ne.lat()
																	+ ","
																	+ ne.lng()
																	+ " "
																	+ sw.lat()
																	+ ","
																	+ bbox;
															jQuery("#bbox")
																	.val(
																			"("
																					+ bbox
																					+ ")");
															jQuery("#nex").val(
																	ne.lng());
															jQuery("#ney").val(
																	ne.lat());
															jQuery("#swx").val(
																	sw.lng());
															jQuery("#swy").val(
																	sw.lat());
															if (onChange)
																onChange();
														}, 1000);

											});

						},

						detectedBrowser : function() {

							var useragent = navigator.userAgent;
							if (useragent.indexOf('iPhone') != -1
									|| useragent.indexOf('Android') != -1) {
								this.map.style.width = '100%';
								this.map.style.height = '100%';
							} else {
								this.map.style.width = '600px';
								this.map.style.height = '800px';
							}
						},

						addProperty : function(property) {
							if (!this.properties[property.id]) {
								this.properties[property.id] = property;
								this._createMarker(property);
								this.markers.push(property.marker);
							} else {
								var marker = this.properties[property.id].marker;
								this.properties[property.id] = property;
								property.marker = marker;
								marker.setContent(this
										._createMarkerContent(property));
							}

						},
						// AGRUPAR MARCADORES
						// renderProperties : function() {
						//
						// // google.maps.event.clearListeners(this.map,
						// // 'click');
						// $.each(this.markers, function() {
						// this.setMap(null);
						// });
						// if (this.mc)
						// this.mc.clearMarkers();
						// this.mc = new MarkerClusterer(this.map,
						// this.markers);
						//
						// },
						clearProperties : function() {
							$.each(this.markers, function() {
								this.setMap(null);
							});
							this.properties = {};
							this.markers = [];

						},
						_createMarker : function(property) {
							var pos = new google.maps.LatLng(property.lat,
									property.lng);
							property.marker = new RichMarker({
								position : pos,
								map : this.map,
								draggable : false,
								content : this._createMarkerContent(property),
								flat : true,
								clickable : true,
								anchor : RichMarkerPosition.BOTTOM,

							});
							var context = this;
							google.maps.event.addListener(property.marker,
									'click', function() {
										context.selectProperty(property.id);
									});
						},

						selectProperty : function(id) {
							var property = this.properties[id];
							this.map.setCenter(property.marker.getPosition());
							this.loadData(property.id);
							if ($("#data-panel").hasClass("ui-panel-open")) {
								return false;
							}
							$("#show-data").click();

							return false;
						},
						loadData : function(id) {
							var selected = this.properties[id];
							$("#data-address").html(selected.address);
							$("#data-comuna").html(selected.comuna);
							$("#data-date").html(selected.created);
							$("#data-last").html(selected.visited);
							$("#data-visits").html(selected.visits);

							var perseption = "";
							switch (selected.perseption) {

							case geomanagement.PropertyPerseption.LOW:
								perseption = "Baja";
								break;
							case geomanagement.PropertyPerseption.MID:
								perseption = "Media";
								break;
							case geomanagement.PropertyPerseption.HI:
								perseption = "Alta";
								break;
							}
							$("#data-perseption").html(perseption);
							$("#data-responsable").html(selected.responsable);
							$("#data-number").html(selected.number);
							$("#data-href").attr(
									{
										"href" : this.baseUrl
												+ "/consultar_propiedad/"
												+ selected.number
									});
							$("#data-href-2").attr(
									{
										"href" : this.baseUrl
												+ "/crear_visita/"
												+ selected.number
									});
							$("#data-href-3").attr(
									{
										"href" : this.baseUrl
												+ "/finalizar_agendar_visita/"
												+ selected.number
									});
							this._datosVisitas(selected.listVisita);
							// console.log(selected.listVisita);

						},
						_datosVisitas : function(lista) {
							var ul = $("#data-listVisitsPending tbody")
									.html("");
							var context = this;
							$
									.each(
											lista,
											function(index, element) {
												$(
														"<tr><td>"
																+ element.cliente
																+ " </td><td><a href='"
																+ context.baseUrl
																+ "/finalizar_visita/"
																+ element.id
																+ "?origen=1' class='ui-btn ui-mini ui-btn-b' data-ajax='false' >Gestionar</a></tr></td>")
														.appendTo(ul);
											});
						},
						_createMarkerContent : function(property) {
							var main = $("<div/>").addClass("marker main");
							if (property.type == geomanagement.PropertyTypes.HOUSE)
								main.addClass("house");
							else if (property.type == geomanagement.PropertyTypes.APPARTMENT)
								main.addClass("app");
							else if (property.type == geomanagement.PropertyTypes.AGR)
								main.addClass("agr");
							else if (property.type == geomanagement.PropertyTypes.BOD)
								main.addClass("bod");
							else if (property.type == geomanagement.PropertyTypes.COM)
								main.addClass("com");
							else if (property.type == geomanagement.PropertyTypes.EST)
								main.addClass("est");
							else if (property.type == geomanagement.PropertyTypes.OFI)
								main.addClass("ofi");
							else if (property.type == geomanagement.PropertyTypes.SIT)
								main.addClass("sit");
							else if (property.type == geomanagement.PropertyTypes.MIN) {
								main.addClass("min");
							}
							switch (property.visits) {

							case 0:
								main.addClass("low");
								break;
							case 1:
							case 2:
								main.addClass("mid");
								break;
							default:
								main.addClass("hi");
								break;
							}
							var sold = false;
							switch (property.status) {
							case geomanagement.PropertyStatus.SOLD_BY_ME:
								main.removeClass('hi low mid').addClass(
										"sold_by_me");
								sold = true;
								break;
							case geomanagement.PropertyStatus.SOLD_BY_OTHER:
								main.removeClass('hi low mid').addClass(
										"sold_by_other");
								sold = true;
								break;
							case geomanagement.PropertyStatus.RESERVED:
								main.removeClass('hi low mid').addClass(
										'reserved');
								sold = false;
								break;
							}
							if (property.furinture) {
								$("<div/>").addClass("forniture marker inner")
										.appendTo(main);
							} else {
								$("<div/>").addClass("marker inner").appendTo(
										main);
							}
							if (property.offer) {
								$("<div/>").addClass("offer marker inner")
										.appendTo(main);
							} else {
								$("<div/>").addClass("marker inner").appendTo(
										main);
							}

							var rentOrSale = $("<div/>").addClass(
									"marker inner");
							if (property.rentOrSale == geomanagement.RentOrSale.RENT) {
								rentOrSale.addClass("rent");
							} else {
								rentOrSale.addClass("sale");
							}
							rentOrSale.appendTo(main);
							if (!sold) {
								var arrows = $("<div/>").addClass("arrow")
										.appendTo(main);
								switch (property.perseption) {
								case geomanagement.PropertyPerseption.NONE:
									arrows.addClass("none");
									break;
								case geomanagement.PropertyPerseption.LOW:
									arrows.addClass("low");
									break;
								case geomanagement.PropertyPerseption.MID:
									arrows.addClass("mid");
									break;
								case geomanagement.PropertyPerseption.HI:
									arrows.addClass("hi");
									break;
								}
							}
							if (property.number) {
								$("<div/>").addClass("number marker inner")
										.html(property.number).appendTo(main);
							} else {
								$("<div/>").addClass("marker inner").appendTo(
										main);
							}
							return main[0];
						},
						addResultCount : function(count) {
							$("#result_count").html(count);
						},
						search : function(url, form, clear) {
							waitForIt(true);
							if (clear)
								this.clearProperties();
							var modified = $(form)[0].modified.value;
							var data = this.filter;
							if (modified == 'true' || !data)
								data = $(form).serialize();
							$(form)[0].modified.value = 'false';
							this.filter = data;
							var context = this;
							$.post(
									url,
									data,
									function(data) {
										context.addResultCount(data.count);
										$.each(data.propiedades, function(
												index, element) {
											context.addProperty(element);
										});
										// context.renderProperties();
									}).always(function() {
								waitForIt(false);
							});

						},
						showMyPos : function() {

							this.posMarker = new google.maps.Marker(
									{
										icon : new google.maps.MarkerImage(
												'//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
												new google.maps.Size(22, 22),
												new google.maps.Point(0, 18),
												new google.maps.Point(11, 11)),
									});
							this._getMyPos();
							this.posMarker.setMap(this.map);
							var context = this;
							setInterval(function() {
								context._getMyPos();
							}, 3000);
						},
						whereAmI : function() {
							this.map.setCenter(this.posMarker.getPosition());
						},
						_getMyPos : function() {
							var context = this;
							if (navigator.geolocation) {
								browserSupportFlag = true;
								navigator.geolocation
										.getCurrentPosition(
												function(position) {
													var myPos = new google.maps.LatLng(
															position.coords.latitude,
															position.coords.longitude);
													context.posMarker
															.setPosition(myPos);

												},
												function() {
													context
															._handleNoGeolocation(browserSupportFlag);
												});
							}
							// Browser doesn't support Geolocation
							else {
								browserSupportFlag = false;
								context
										._handleNoGeolocation(browserSupportFlag);
							}

						},
						_handleNoGeolocation : function(errorFlag) {
							if (errorFlag == true) {
								console
										.log("Error en servicio de Geolocalizacion.");
								// initialLocation = newyork;
							} else {
								console
										.log("Su navegador no soporta geolocalizacion");
								// initialLocation = siberia;
							}
						}

					});

})(jQuery);